#coding = 'utf8' 
import sys
import urllib
import urllib2
import traceback
import base64

import Utils.megavideo
import Utils.utilities
from Utils.BeautifulSoup import *
from Utils.XbmcHandler import XbmcHandler

ONLINE_PLUGIN_URL    = "http://www.xbmcplugin.somee.com"
OFFLINE_PLUGIN_URL   = "http://localhost:51290/AllInOnePluginSite/Default.aspx"
PLUGIN_URL           = "plugin-url" 
USE_CACHE            = "usecache"
USERNAME             = "username"
PASSWORD             = "password"

MOVIES_MODE = 1
SERIES_MODE = 2

class NoItemsException(Exception):
   def __init__(self, value):
       self.parameter = value
   def __str__(self):
       return repr(self.parameter)
   
class GenericPluginParser:
                  
    def __init__(self):        
        self.xbmcHandler = XbmcHandler()
        self.settings = {}
        self.loadSettings()

#################################################################################################        
    def loadSettings(self):
        print "-------------------------------------"
        print "loadSettings:"
        print "-------------------------------------"
        self.settings[PLUGIN_URL] = self.xbmcHandler.GetFromSetting(PLUGIN_URL, defaultValue=OFFLINE_PLUGIN_URL)
        self.settings[USE_CACHE] = self.xbmcHandler.GetFromSetting(USE_CACHE, "true")
        self.settings[USERNAME] = self.xbmcHandler.GetFromSetting(USERNAME, "")        
        self.settings[PASSWORD] = self.xbmcHandler.GetFromSetting(PASSWORD, "")
        
        print "PLUGIN_URL:%s" % self.settings[PLUGIN_URL]
        print "USERNAME:%s" % self.settings[USERNAME]
        print "PASSWORD:%s" % self.settings[PASSWORD]  
        print "-------------------------------------"        
        
#################################################################################################
    def HandleMode(self):
        print "Arguments List:[ %s ]" % sys.argv
        
        self.pluginMode = ""
        self.filterType = ""
        self.searchText = ""
        
        params = Utils.utilities.GetParams(sys.argv[2])       
        
        if params.__contains__('url'):
            self.url = urllib.unquote_plus(params['url'])
        else:
            self.url = self.settings[PLUGIN_URL]
          
        params = Utils.utilities.GetParams(self.url)  
        if params.__contains__('PluginMode'):
            self.pluginMode = params['PluginMode']
        
        if params.__contains__('FilterType'):
            self.filterType = params['FilterType']
            
        if params.__contains__('SearchText'):
            self.searchText = params['SearchText']
        
        if(self.settings[USERNAME] != "" and self.settings[PASSWORD] != ""):
            if(self.url.find("default.aspx") == -1):
                self.url = self.url + "/"
                
            if(self.url.find("?") == -1):
                self.url = self.url + "?"
            else:
                self.url = self.url + "&"
            self.url = "%suserName=%s&password=%s" % (self.url, self.settings[USERNAME], self.settings[PASSWORD])
            print self.url     
        
        print "##########################################################"
        print("url: %s" % self.url)
        print "##########################################################"
        
        print "##########################################################"
        print("pluginMode: %s" % self.pluginMode)
        print "##########################################################"
        
        print "##########################################################"
        print("filterType: %s" % self.filterType)
        print "##########################################################"
        
        if(self.filterType == "0" and self.searchText == ""): #SEARCH_MODE
            searchStr = self.xbmcHandler.OpenKeyboard("", "Enter Search Text")
            print "OpenKeyboard: [%s]" % searchStr
            #searchStr = "%D7%94%D7%90%D7%95%D7%A1"
            if(searchStr != None and searchStr != ""):                
                self.url = "%s&SearchText=%s" % (self.url, urllib.quote(searchStr))
                self.parseUrl(decode_url=False)
        else:
            self.parseUrl()            

    def extractItemData(self, itemTag):
        title = self.getItemAsString(itemTag.title)
        description = self.getItemAsString(itemTag.description)
        link = self.getItemAsString(itemTag.link).replace("&amp;", "&")
        category = self.getItemAsString(itemTag.category)
        imageLink = self.getImageLink(itemTag)             
        isFolder = (category == "")  
        return (title, description, link, category, imageLink, isFolder)
                
#################################################################################################
    def addMovieItem(self, title, description, link, category, imageLink, isFolder):
        if(category == "MegaVideo"):
            (flv_link, Original_File,title, description, runtime) = self.extractMegaVideoLink(link)
            print "flv_link: %s" % flv_link
            self.xbmcHandler.PlayVideo(flv_link, title, imageLink)
            
        elif(category == "Movie"):            
             self.xbmcHandler.PlayVideo(link, title, imageLink) 
    
            
#################################################################################################
    def parseUrl(self, decode_url=True): 
        try:       
            print self.url
            source = Utils.utilities.ReadUrlPageData(self.url, decode_url)
            soup = BeautifulStoneSoup(source)
            itemsTag = soup.findAll('item')
            print "parseUrl return with %d items" % len(itemsTag)
            
            if  (len(itemsTag) == 0):
                self.xbmcHandler.ShowMessageBox("Operation Result", "No Items Found")
                return
               
            for itemTag in itemsTag:                
                try:
                    (title, description, link, category, imageLink, isFolder) = self.extractItemData(itemTag)
                    if(title == "Error"):
                        raise Utils.megavideo.MovieNotValidException(description)
                    
                    if(isFolder):                        
                        self.addDirectoryItem(name=title, 
                                              iconimage=imageLink, 
                                              isFolder=isFolder, 
                                              url=link, 
                                              summary=description, 
                                              totalItems=len(itemsTag))
                    else:
                        self.addMovieItem(title, description, link, category, imageLink, isFolder)
                        
                except Utils.megavideo.MovieNotValidException, (instance):
                    self.xbmcHandler.ShowMessageBox("Failed load movie", instance.parameter)
                except:
                    print "got exception while adding item"
                    print '-'*60
                    traceback.print_exc(file=sys.stdout)
                    print '-'*60                   
        
        except:
            print "got exception in parseUrl"
            print '-'*60
            traceback.print_exc(file=sys.stdout)
            print '-'*60
            self.xbmcHandler.ShowMessageBox("unhandled Exception", str(sys.exc_info()[0]))
            raise                             
            
        self.xbmcHandler.endOfDirectory()
            

#################################################################################################
    def decodeUrl(self, url):     
        return urllib.unquote(base64.b64decode(urllib.unquote(url)))  
    
#################################################################################################
    def safeQuoteUrl(self, url):
        try:
             return urllib.quote(str(urllib2.unquote(url)))
        except:
            return url
        
#################################################################################################        
    def extractMegaVideoLink(self, source):
        print "Extract link: %s" % source
        return Utils.megavideo.resolveURL(source, 
                                          self.settings[MEGAUPLOAD_ACCOUNT],
                                          self.settings[MEGAUPLOAD_USERNAME],
                                          self.settings[MEGAUPLOAD_PASSWORD],
                                          cookiepath=Utils.utilities.COOKIE_PATH)    
#################################################################################################        
        
    def getItemAsString(self, item):
        try:
            return item.string
        except:
            return ""
        
#################################################################################################    
    def getImageLink(self, item):
        try:
            if(item.image != None):
                return item.image.url.string
        except:
            pass
        
        return ""
        
#################################################################################################    
    def addDirectoryItem(self, name, iconimage, isFolder, url="", summary="", totalItems=1):        
        if(not self.xbmcHandler.workWithXBMC): return
        urlParams = Utils.utilities.GetParams(url)    
        pluginUrl= "url=%s" % self.safeQuoteUrl(url)
        return self.xbmcHandler.addItem(self.settings[PLUGIN_URL],
                                        self.settings[USERNAME], 
                                        self.settings[PASSWORD],
                                        name=name, 
                                        url=pluginUrl,
                                        urlParams=urlParams,
                                        summary=summary, 
                                        iconimage=iconimage, 
                                        isFolder=isFolder, 
                                        totalItems=totalItems,
                                        trailer="")
   
################################################################################################
if __name__ == "__main__":
    genericPluginParser = GenericPluginParser()
    genericPluginParser.HandleMode()